package me.yuzho.study.concurrency;

import static net.mindview.util.Print.*;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;


class NeedsCleanup {
    private final int id;
    
    public NeedsCleanup(int ident) {
        id = ident;
        print("NeedsCleanup: " + id);
    }
    
    public void cleanup() {
        print("Cleaning up " + id);
    }
}


class Blocked3 implements Runnable {
    private volatile double d = 0.0;
    
    public void run() {
        
        try {
            while(!Thread.interrupted()) {
                // point1
                NeedsCleanup n1 = new NeedsCleanup(1);
                // Guarantee proper cleanup of n1
                try {
                    print("Sleeping");
                    TimeUnit.SECONDS.sleep(1); //中断标志在些设置时，会触发中断异常
                    
                    NeedsCleanup n2 = new NeedsCleanup(2);
                    //Guarantee proper cleanup of n2
                    
                    try {
                        print("Calculating");
                        
                        // A time consuming. Non-blocking operation
                        for(int i=1; i<2500000; i++) { //中断标志在些设置时，不会触发异常，会等待此次执行结束后退出while循环
                            d = d + (Math.PI + Math.E) / d;
                        }
                        
                        print("Finished time-consuming operation");
                        
                    } finally {
                        n2.cleanup();
                    }
                    
                } finally {
                    n1.cleanup();
                }
            }
            print("Exiting via while() test");
        } catch (InterruptedException e) {
            print("Exiting via InterruptedException");
        }
    }
}

/** 检查中断的通常用法
 * @author yzhou-citrix
 *
 */
public class InterruptingIdiom {

    public static void main(String[] args) throws NumberFormatException, InterruptedException {
        /*if(args.length != 1) {
            print("usage: java InterruptingIdiom delay-in-ms");
        }*/
        args = (String[]) Arrays.asList("1000").toArray();
        
        Thread t = new Thread(new Blocked3());
        t.start();
        
        TimeUnit.MILLISECONDS.sleep(new Integer(args[0]));
        
        t.interrupt();
    }
}
